package cn.shengchao.controler.wecom;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeNodeInfo;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeNodeInfoService;
import cn.shengchao.examstar.me.collect.acl.adapters.repositories.UserCollectInfoRepository;
import cn.shengchao.examstar.me.course.domain.ContactUserLearning;
import cn.shengchao.examstar.me.course.domain.CourseStatisticVo;
import cn.shengchao.examstar.me.course.ohs.local.appervices.ContactUserCourseStatisticAppService;
import cn.shengchao.examstar.me.infrastructure.dao.po.UserCollectInfo;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeSaleRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeTypeEnum;
import cn.shengchao.examstar.rpc.wecom.resp.ContactUserPictureVo;
import cn.shengchao.examstar.rpc.wecom.resp.CourseLearningVo;
import cn.shengchao.examstart.user.acl.adapters.repositories.UserRepository;
import cn.shengchao.examstart.user.domain.entity.User;
import cn.shengchao.qywx.infrastrure.po.QywxCustomer;
import cn.shengchao.qywx.infrastrure.service.QywxCustomerService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.continew.starter.web.model.R;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: examstarapi
 * @description: 用户画像（信息采集）业务
 * @author: Xiong weiqiang
 * @create: 2025-04-18 17:00
 */

@RestController
@Slf4j
@CrossOrigin("${project.cross-origin}")
@RequestMapping("/api/${project.version}/qywx")
public class ContactUserCollectInfoController {
    @Autowired
    private  QywxCustomerService qywxCustomerService;
    @Autowired
    ContactUserCourseStatisticAppService contactUserCourseStatisticAppService;
    @Autowired
    UserRepository userRepository;
    @Autowired
    UserCollectInfoRepository userCollectInfoRepository;

    @Autowired
    DistributeNodeInfoService distributeNodeInfoService;
    /**
     * 用户画像获取
     * @param userKey
     * @param type 0 unionId 1 externalUserId,2 phone,3 userId
     * @return
     * @throws Exception
     */
    @SaIgnore
    @GetMapping("/getContactUserPicture/{userKey}")
    public R<ContactUserPictureVo> getContactUserPictureVo(@PathVariable String userKey, Integer type) throws Exception{
        ContactUserPictureVo contactUserPictureVo=new ContactUserPictureVo();
        type=ObjUtil.defaultIfNull(type,0);
        User user=getUserByType(userKey, type);

        if (user!=null){
            QywxCustomer qywxCustomer=null;
            if (type==0){
                List<QywxCustomer> qywxCustomers=qywxCustomerService.list(new LambdaQueryWrapper<>(QywxCustomer.class).eq(QywxCustomer::getUnionId,userKey));
                if (CollUtil.isNotEmpty(qywxCustomers)){
                    qywxCustomer=qywxCustomers.getFirst();
                }
            }
            if (type==1){
                List<QywxCustomer> qywxCustomers=qywxCustomerService.list(new LambdaQueryWrapper<>(QywxCustomer.class).eq(QywxCustomer::getExternalUserId,userKey));
                if (CollUtil.isNotEmpty(qywxCustomers)){
                    qywxCustomer=qywxCustomers.getFirst();
                }
            }
            if (type==2 || type==3){
                List<QywxCustomer> qywxCustomers=qywxCustomerService.list(new LambdaQueryWrapper<>(QywxCustomer.class).eq(QywxCustomer::getSysUserId,user.getId()));
                if (CollUtil.isNotEmpty(qywxCustomers)){
                    qywxCustomer=qywxCustomers.getFirst();
                }
            }
            if (qywxCustomer!=null){
                contactUserPictureVo.setContactAvatar(qywxCustomer.getAvatar());
                contactUserPictureVo.setContactName(qywxCustomer.getName());
                contactUserPictureVo.setContactGender(Integer.valueOf(qywxCustomer.getGender()));
            }
            contactUserPictureVo.setSysUserId(user.getId());
            contactUserPictureVo.setPhone(user.getPhone());
            UserCollectInfo collectInfo=userCollectInfoRepository.getUserCollectInfo(user.getId());
            contactUserPictureVo.setGradeLevel(contactUserPictureVo.getGradeLevel());
            contactUserPictureVo.setGradeType(collectInfo.getGradeType());
            contactUserPictureVo.setSysUserAvatar(user.getAvatar());
            contactUserPictureVo.setNickName(user.getName());
            contactUserPictureVo.setSysGender(user.getGender());
            contactUserPictureVo.setRegisterTime(LocalDateTimeUtil.format(user.getCreateTime(),"yyyy-MM-dd"));
            DistributeNodeInfo nodeInfo=distributeNodeInfoService.getNodeInfoForUser(user.getId(), DistributeTypeEnum.TYPE_SALE);
            if (nodeInfo!=null&& DistributeSaleRoleEnum.ROLE_SLMB.getCode().equals(nodeInfo.getDistributeRoleCode())){
                contactUserPictureVo.setVipLevel(1);
            }else {
                contactUserPictureVo.setVipLevel(0);
            }
            contactUserPictureVo.setSourceChanel("");
            CourseStatisticVo statistic=contactUserCourseStatisticAppService.statisticUserCourseLearning(user.getId());
            contactUserPictureVo.setFinishCourseSum(statistic.getFinishCourseNum());
            contactUserPictureVo.setCourseSum(statistic.getCourseTotalNum());
            contactUserPictureVo.setLearningCourseSum(statistic.getInLearningCourseNum());
            contactUserPictureVo.setPayKnowledgeNodeSum(statistic.getPayKnowledgeNodeNum());
            contactUserPictureVo.setFinishSeconds(statistic.getCourseSecondTotal());
            contactUserPictureVo.setPayKnowledgeNodeSum(statistic.getPayKnowledgeNodeNum());
            contactUserPictureVo.setPayKnowledgeNodePriceSum(statistic.getPayKnowledgeNodePriceSum());
            contactUserPictureVo.setFreeUnlockKnowledgeNodeSum(statistic.getFreeUnlockKnowledgeNodeNum());
            contactUserPictureVo.setFreeUnlockKnowledgeNodePriceSum(statistic.getFreeUnlockKnowledgeNodePriceSum());
            contactUserPictureVo.setLastLearnTime(statistic.getLastLearnTime());
            List<CourseLearningVo> learningCourse=new ArrayList<>();
            //
            if (CollUtil.isNotEmpty(statistic.getCourseLearningVoList())){
                for (ContactUserLearning learning:statistic.getCourseLearningVoList()){
                    CourseLearningVo courseLearningVo=new CourseLearningVo();
                    courseLearningVo.setCourseId(learning.getCourseId());
                    courseLearningVo.setCourseName(learning.getCourseName());
                    courseLearningVo.setImgUrl(learning.getImgUrl());
                    courseLearningVo.setLearnProgress(learning.getLearnProgress());
                    courseLearningVo.setLastLearnTime(learning.getLastLearnTime());
                    learningCourse.add(courseLearningVo);
                }
            }
            contactUserPictureVo.setLearningCourse(learningCourse);
        }
        return R.ok(contactUserPictureVo);
    }

    /**
     * 查询
     * @param externalUserId
     * @param type 0 unionId 1 externalUserId,2 phone,3 userId
     * @param courseName
     * @return
     * @throws Exception
     */

    @SaIgnore
    @GetMapping("/getContactUserLearnCourses/{externalUserId}")
    public R<List<CourseLearningVo>> getContactUserLearnCourses(@PathVariable String externalUserId,String courseName, Integer type) throws Exception{
        List<CourseLearningVo> learningVoList=new ArrayList<>();
        type=ObjUtil.defaultIfNull(type,0);
        User user=getUserByType(externalUserId,type);

        if (user != null) {
            List<ContactUserLearning> learningList = contactUserCourseStatisticAppService.queryUserCourseLearning(courseName, null, user.getId());
            if (CollUtil.isNotEmpty(learningList)) {
                for (ContactUserLearning learning : learningList) {
                    CourseLearningVo courseLearningVo = new CourseLearningVo();
                    courseLearningVo.setCourseId(learning.getCourseId());
                    courseLearningVo.setCourseName(learning.getCourseName());
                    courseLearningVo.setPrice(learning.getPrice());
                    courseLearningVo.setClassHour(learning.getClassHour());
                    courseLearningVo.setLearnSecondTotal(learning.getUserLearningSecondTotal());
                    courseLearningVo.setKnowledgeNodeNum(learning.getKnowledgeNodeNum());
                    courseLearningVo.setUnLockKnowledgeNodeNum(learning.getFreeUnlockKnowledgeNodeNum());

                    courseLearningVo.setCourseName(learning.getCourseName());
                    courseLearningVo.setImgUrl(learning.getImgUrl());
                    courseLearningVo.setLearnProgress(learning.getLearnProgress());
                    courseLearningVo.setLastLearnTime(DateUtil.format((learning.getLastLearnTimeSecond() == 0L ? new Date() : new Date(learning.getLastLearnTimeSecond())), "yyyy-MM-dd HH:mm:ss"));
                    learningVoList.add(courseLearningVo);
                }
            }
        }
        return R.ok(learningVoList);
    }

    private User getUserByType(String userKey, int type) throws Exception {
        User user = null;
        switch (type){
            case 0: user = userRepository.ofUnionId(userKey); break;
            case 1: {
                QywxCustomer qywxCustomer = null;
                List<QywxCustomer> qywxCustomers = qywxCustomerService.list(new LambdaQueryWrapper<>(QywxCustomer.class).eq(QywxCustomer::getExternalUserId, userKey));
                if (CollUtil.isNotEmpty(qywxCustomers)) {
                    qywxCustomer = qywxCustomers.getFirst();
                    if (StrUtil.isNotBlank(qywxCustomer.getUnionId())){
                        user = userRepository.ofUnionId(qywxCustomer.getUnionId());
                    }
                }
                break;
            }
            case 2: {
                List<User> users = userRepository.selectByPhone(userKey);
                if (CollUtil.isNotEmpty(users)) {
                    user = users.getFirst();
                }
                break;
            }
            case 3: {
                user = userRepository.of(Long.valueOf(userKey));
                break;
            }
            default:
                break;
        }
        return user;
    }
}